package com.aos.iot.socket.udp;

import com.aos.iot.socket.udp.properties.SocketUdpProperties;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;

@Slf4j
@RequiredArgsConstructor
public class SocketUdpServer {

    private final EventLoopGroup udpBossGroup;

    private final ChannelInitializer<? extends Channel> channelInitializer;

    private final SocketUdpProperties socketUdpProperties;

    private Bootstrap bootstrap;

    @PostConstruct
    public void init() {
        bootstrap = new Bootstrap()
                .group(udpBossGroup)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(channelInitializer);
    }

    public void start() throws InterruptedException {
        bootstrap.bind(socketUdpProperties.getHost(), socketUdpProperties.getPort())
                .sync()
                .addListener(future -> {
                    if (future.isSuccess()) {
                        log.info("Socket Udp server started at port: {}", socketUdpProperties.getPort());
                    }
                });
    }

    @SneakyThrows
    public synchronized void stop() {
        udpBossGroup.shutdownGracefully().await();
    }

}
